//
//  MyCollectionViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/31.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "MyCollectionViewController.h"
#import "MyCollectionCell.h"
#import "MainNavigationController.h"
#import "NewsListModel.h"
#import "NewsDetailViewController.h"
#import "SQLiteManager.h"
#import <MJExtension/MJExtension.h>
#import "JKPopoverTool.h"

@interface MyCollectionViewController ()
/** story模型数组 */
@property (nonatomic, strong) NSMutableArray *stories;

/** 没有收藏的图标 */
@property (nonatomic, weak) UIImageView *noCollectionImgView;

/** 没有收藏的label */
@property (nonatomic, weak) UILabel *noCollectionLabel;

/** 当前皮肤模式 */
@property (nonatomic, copy) NSString *currentSkinModel;

/** 取消按钮 */
@property (nonatomic, weak) UIButton *cancelBtn;

/** 删除按钮 */
@property (nonatomic, weak) UIButton *deleteBtn;
@end

@implementation MyCollectionViewController

static NSString *collectionReuseID = @"myCollectionCell";

#pragma mark - 懒加载
- (NSMutableArray *)stories{
    if (!_stories) {
        _stories = [NSMutableArray array];
    }
    return _stories;
}

- (UIButton *)cancelBtn{
    if (!_cancelBtn) {
        UIButton *cancelBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        cancelBtn.hidden = YES;
        cancelBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        cancelBtn.frame = self.navBarView.leftButtonFrame;
        cancelBtn.contentMode = UIViewContentModeBottomLeft;
        [cancelBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [cancelBtn setTitleColor:[UIColor grayColor] forState:(UIControlStateHighlighted)];
        [cancelBtn setTitle:@"取消" forState:(UIControlStateNormal)];
        [cancelBtn addTarget:self action:@selector(cancel:) forControlEvents:(UIControlEventTouchUpInside)];
        [self.view addSubview:cancelBtn];
        _cancelBtn = cancelBtn;
    }
    return _cancelBtn;
}

- (UIButton *)deleteBtn{
    if (!_deleteBtn) {
        UIButton *deleteBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        deleteBtn.hidden = YES;
        deleteBtn.frame = self.navBarView.rightButtonFrame;
        deleteBtn.enabled = NO;
        [deleteBtn setTitle:@"删除" forState:(UIControlStateNormal)];
        [deleteBtn setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
        [deleteBtn setTitleColor:[[UIColor redColor] colorWithAlphaComponent:0.8] forState:(UIControlStateHighlighted)];
        [deleteBtn setTitleColor:[[UIColor redColor] colorWithAlphaComponent:0.6] forState:(UIControlStateDisabled)];
        [deleteBtn addTarget:self action:@selector(delete:) forControlEvents:(UIControlEventTouchUpInside)];
        [self.view addSubview:deleteBtn];
        _deleteBtn = deleteBtn;
    }
    return _deleteBtn;
}

- (UIImageView *)noCollectionImgView{
    if (!_noCollectionImgView) {
        UIImageView *imgV = [[UIImageView alloc] init];
        imgV.image = [UIImage imageNamed:@"Menu_Icon_Collect"];
        imgV.hidden = YES;
        [self.view addSubview:imgV];
        _noCollectionImgView = imgV;
    }
    return _noCollectionImgView;
}

- (UILabel *)noCollectionLabel{
    if (!_noCollectionLabel) {
        UILabel *lb = [[UILabel alloc] init];
        lb.text = @"还没有收藏内容";
        lb.textColor = JKColor(168, 168, 168);
        lb.font = [UIFont systemFontOfSize:14];
        lb.hidden = YES;
        [lb sizeToFit];
        lb.width = JKScreenW;
        lb.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:lb];
        _noCollectionLabel = lb;
    }
    return _noCollectionLabel;
}

#pragma mark - 生命周期方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkin) name:JKSkinModelDidChangedNotification object:nil];
    [self updateSkin];
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view removeGestureRecognizer:self.pan];
    self.pan = nil;
    
    self.navBarView.title = @"我的收藏";
    __weak typeof(self) weakSelf = self;
    [self.navBarView setBackBtnClickBlock:^(UIButton *btn) {
        MainNavigationController *mainNav = (MainNavigationController *)weakSelf.navigationController;
        !mainNav.backBtnBlock ? : mainNav.backBtnBlock();
    }];
    
    UIButton *rightBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    rightBtn.frame = CGRectMake(JKScreenW - (JKNavBarHeight - JKStatusBarHeight) + 3, JKStatusBarHeight + 2, JKNavBarHeight - JKStatusBarHeight, JKNavBarHeight - JKStatusBarHeight);
    [rightBtn setImage:[UIImage imageNamed:@"ic_more"] forState:(UIControlStateNormal)];
    [rightBtn addTarget:self action:@selector(moreClick) forControlEvents:(UIControlEventTouchUpInside)];
    self.navBarView.rightButton = rightBtn;
    
    // 去除多余分隔线
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MyCollectionCell class]) bundle:nil] forCellReuseIdentifier:collectionReuseID];
    
    [self loadData];
}

- (void)moreClick{
    JKPopoverItem *item1 = [JKPopoverItem itemWithTitle:@"批量编辑" normalImage:@"ic_bulkEditing" highlightedImage:nil];
    JKPopoverItem *item2 = [JKPopoverItem itemWithTitle:@"全部删除" normalImage:@"ic_delete" highlightedImage:nil];
    NSArray *itemsArr = @[item1, item2];
    __weak typeof(self) weakSelf = self;
    [[JKPopoverTool showWithPopoverItems:itemsArr popFrame:CGRectMake(self.view.width - 120 - 2, JKNavBarHeight + 1, 130, JKNavBarHeight) rowHeight:30] setSelectedIndexBlock:^(NSInteger index) {
        switch (index) {
            case 0:
                [weakSelf bulkEditing];
                break;
                
            case 1:
                [weakSelf removeAllCollections];
                break;
                
            default:
                break;
        }
    }];
}

// 批量编辑，交给子类调用
- (void)bulkEditingWithNoticeTitle:(NSString *)title{
    if (self.stories.count == 0) {
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:title preferredStyle:(UIAlertControllerStyleAlert)];
        
        [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil]];
        [self presentViewController:alertVc animated:YES completion:nil];
        return;
    }
    [self enterEditingModel];
}

// 批量编辑
- (void)bulkEditing{
    [self bulkEditingWithNoticeTitle:@"您还没有收藏文章哦~"];
}

// 进入编辑模式
- (void)enterEditingModel{
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:(UITableViewRowAnimationAutomatic)];
    // 允许在编辑模式进行多选操作
    self.tableView.allowsMultipleSelectionDuringEditing = YES;
    [self.tableView setEditing:YES animated:YES];
    self.cancelBtn.hidden = NO;;
    self.deleteBtn.hidden = NO;
    self.navBarView.leftButtonHidden = YES;
    self.navBarView.rightButtonHidden = YES;
}

// 退出编辑模式
- (void)exitEditingModel{
    [self.tableView setEditing:NO animated:YES];
    self.navBarView.leftButtonHidden = NO;
    self.navBarView.rightButtonHidden = NO;
    self.cancelBtn.hidden = YES;
    self.deleteBtn.hidden = YES;
    
    if (self.stories.count == 0) {
        [self showNoCollection];
    }
}

// 取消
- (void)cancel:(UIButton *)btn{
    [self exitEditingModel];
}

// 删除
- (void)delete:(UIButton *)btn{
    // 获得所有被选中的行
    NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
    
    // 遍历所有的行号
    NSMutableArray *deletedStories = [NSMutableArray array];
    NSMutableArray *deletedStoryIDs = [NSMutableArray array];
    for (NSIndexPath *indexPath in indexPaths) {
        NewsListModel *model = self.stories[indexPath.row];
        [deletedStories addObject:model];
        [deletedStoryIDs addObject:@(model.ID)];
    }
    
    // 更新为未收藏状态
    [SQLiteManager updateCollectionsCancelWithStoryIDs:deletedStoryIDs];
    
    // 删除模型数据
    [self.stories removeObjectsInArray:deletedStories];
    [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:(UITableViewRowAnimationAutomatic)];
    
    // 最后再退出编辑模式
    [self exitEditingModel];
}

// 移除所有 交给子类调用
- (void)removeAllWithNoticeTitle:(NSString *)title{
    if (self.stories.count == 0) {
        [self bulkEditing];
        return;
    }
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:(UIAlertControllerStyleAlert)];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"再想想" style:(UIAlertActionStyleCancel) handler:nil]];
    [alertVc addAction:[UIAlertAction actionWithTitle:@"全部删除" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        
        // 更新为未收藏状态
        NSArray *IDs = [self.stories valueForKeyPath:@"ID"];
        [SQLiteManager updateCollectionsCancelWithStoryIDs:IDs];
        [self loadData];
    }]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

// 移除所有收藏
- (void)removeAllCollections{
    [self removeAllWithNoticeTitle:@"确认要全部删除吗？"];
}

// 加载数据
- (void)loadData{
    [self.stories removeAllObjects];
    NSArray *stories = [SQLiteManager queryCollectedStoryList];
    
    if (stories.count == 0) {
        [self showNoCollection];
        return;
    }
    [self hideNothingNotice];
    
    stories = [NewsListModel mj_objectArrayWithKeyValuesArray:stories];
    [self.stories addObjectsFromArray:stories];
    [self.tableView reloadData];
}

// 隐藏什么都没有的提示，交给子类调用
- (void)hideNothingNotice{
    self.tableView.hidden = NO;
    [self.noCollectionImgView removeFromSuperview];
    [self.noCollectionLabel removeFromSuperview];
}

// 显示 什么都没有 交给子类调用
- (void)showNothingWithTitle:(NSString *)title image:(UIImage *)image{
    self.tableView.hidden = YES;
    self.noCollectionImgView.frame = CGRectMake((JKScreenW - 30) * 0.5, 180, 30, 30);
    self.noCollectionLabel.centerX = self.noCollectionImgView.centerX;
    self.noCollectionLabel.y = self.noCollectionImgView.y + 30 + 15;
    self.noCollectionImgView.hidden = NO;
    self.noCollectionLabel.hidden = NO;
    
    if (title) {
        self.noCollectionLabel.text = title;
    }
    if (image) {
        self.noCollectionImgView.image = image;
    }
}

// 显示 未收藏
- (void)showNoCollection{
    [self showNothingWithTitle:nil image:nil];
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.stories.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCollectionCell *cell = [tableView dequeueReusableCellWithIdentifier:collectionReuseID];
    
    NewsListModel *model = self.stories[indexPath.row];
    cell.model = model;
    
    // 切换皮肤
    if ([self.currentSkinModel isEqualToString:JKNightSkinModelValue]) {
        [cell changeToNightSkin];
        
    }else{
        [cell changeToDaySkin];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    return cell;
}

#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView.isEditing) {
        self.deleteBtn.enabled = YES;
        return;
    }
    
    NewsDetailViewController *vc = [[NewsDetailViewController alloc] init];
    NewsListModel *model = self.stories[indexPath.row];
    vc.storyID = model.ID;
    vc.themeStories = self.stories;
    vc.indexPath = indexPath;
    vc.backgroundImageUrl = @"http://p3.zhimg.com/ff/15/ff150eef63a48f0d1dafb77e62610a9f.jpg";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *indexPaths = [tableView indexPathsForSelectedRows];
    if (indexPaths.count == 0) {
        self.deleteBtn.enabled = NO;
    }
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *action = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"取消收藏" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        // 更新为未收藏状态
        NewsListModel *model = self.stories[indexPath.row];
        [SQLiteManager updateCollectedStatusWithStoryID:model.ID collected:NO];
        
        // 删除指定行cell
        [self.stories removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationFade)];
        if (self.stories.count == 0) {
            [self showNoCollection];
        }
    }];
    
    return @[action];
}

#pragma mark - 更新皮肤
- (void)updateSkin{
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    self.currentSkinModel = currentSkinModel;
    
    if ([currentSkinModel isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        self.view.backgroundColor = JKNightSkinColor;
        [self.navBarView changeToNightSkin];
        
    }else{ // 日间模式
        self.view.backgroundColor = JKGlobalBgColor;
        [self.navBarView changeToDaySkin];
    }
    [self.tableView reloadData];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
